package com.imay.live.fragment.discovery;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.imay.live.R;
import com.imay.live.activity.RoomPushShortActivity;
import com.imay.live.activity.discovery.SupperDekaronActivity;
import com.imay.live.adapter.SupperDekaronAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.model.SupperModel;
import com.imay.live.model.SupperStatModel;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.view.SupperScrollView;
import com.imay.live.view.custom.SupperDekaronLayout;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;

import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * 超胆播
 * Created by Administrator on 2017/3/27.
 */

public class SupperFragment extends LoadFragment {
    public static final int DATACOUNT = 5;
    private View noMoreView;
    private boolean loadmore = true;

    public static SupperFragment newInstance() {
        return new SupperFragment();
    }

    @Override
    public void onResume() {
        super.onResume();
        mRefreshLayout.setEnableLoadmore(loadmore);
    }

    @Override
    public void setTabH(int tabH) {
        addFooterView(tabH);
    }

    @Override
    public boolean getsetEnableRefresh() {
        if (mLinearRecyclerView != null) {
            RecyclerView.LayoutManager layoutManager = mLinearRecyclerView.getLayoutManager();
            if (layoutManager instanceof LinearLayoutManager) {
                int index = ((LinearLayoutManager) layoutManager).findFirstCompletelyVisibleItemPosition();
                return index == 0;
            }
        }
        return super.getsetEnableRefresh();
    }

    @Override
    public void setVisibleHint(boolean isVisible) {
        if (mLinearRecyclerView != null) {
            if (mLinearRecyclerView.getChildCount() > 1)
                for (int i = 0; i < mLinearRecyclerView.getChildCount(); i++) {
                    if (mLinearRecyclerView.getChildAt(i) instanceof LinearLayout) {
                        LinearLayout linearLayout = (LinearLayout) mLinearRecyclerView.getChildAt(i);
                        if (linearLayout.getChildCount() > 1) {
                            View view = linearLayout.getChildAt(1);
                            if (view instanceof SupperScrollView) {
                                SupperScrollView supperScrollView = (SupperScrollView) view;
                                supperScrollView.setAntion(isVisible ? View.VISIBLE : View.INVISIBLE);
                            }
                        }
                    }
                }
        }
    }

    public void onRequestSuccess(String command, String data) {
        try {
            Result<ArrayList<SupperModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<SupperModel>>>() {
            }.getType());
            if (result.result == CodeSuccess && result.data != null) {
                mdatas.clear();
                if (noMoreView.getParent() != null) {
                    loadmore = true;
                    mAdapter.removeFooterView(noMoreView);
                }
                for (SupperModel supperModel : result.data) {
                    if (supperModel.getShortLiveInfos() != null && supperModel.getShortLiveInfos().size() > 0) {
                        mdatas.add(supperModel);
                    }
                }
                mpapecount = result.data.size();
                if (mpapecount == 0) {
                    loadError(getResources().getString(R.string.str_nodata));
                } else {
                    mAdapter.notifyDataSetChanged();
                    if (mRefreshLayout.getOnScrollListener() != null) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mRefreshLayout.getOnScrollListener().onScrolled();
                            }
                        });
                    }
                    if (mpapecount > 0) {
                        addFooterView(tabH);
                    }
                    completeLoad(mpapecount == 0);
                }
            } else {
                loadError(getResources().getString(R.string.str_loaderror));
            }

        } catch (Exception e) {
            loadError(getResources().getString(R.string.str_loaderror));
        }
    }

    public void onRequestError(String command, int code, String message) {
        loadError(getResources().getString(R.string.str_loaderror));
    }

    public void onStatSuccess(String command, String data) {
        try {
            Result<SupperStatModel> result = JSON.parseObject(data, new TypeReference<Result<SupperStatModel>>() {
            }.getType());
            if (result.result == CodeSuccess && result.data != null) {
            } else {
            }

        } catch (Exception e) {
        }
    }

    public void onStatError(String command, int code, String message) {

    }

    public void onLoadMore() {
        ProtoRequestHelper.task(ProtoHttpFactory.getShortLive(mpapecount, DATACOUNT)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<ArrayList<SupperModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<SupperModel>>>() {
                    }.getType());
                    if (result.result == CodeSuccess && result.data != null) {
                        int oldcount = mdatas.size();
                        for (SupperModel supperModel : result.data) {
                            if (supperModel.getShortLiveInfos() != null && supperModel.getShortLiveInfos().size() > 0) {
                                mdatas.add(supperModel);
                            }
                        }
                        int newcount = mdatas.size() - oldcount;
                        mpapecount = result.data.size() + mpapecount;
                        mAdapter.notifyItemRangeInserted(oldcount - newcount + mAdapter.getHeaderLayoutCount(), newcount);
                        mAdapter.notifyDataSetChanged();
                        if (mRefreshLayout.getOnScrollListener() != null) {
                            mRefreshLayout.getOnScrollListener().onScrolled();
                        }
                        completeLoadmore(DATACOUNT > result.data.size());
                        if (DATACOUNT > result.data.size()) {
                            if (noMoreView.getParent() == null) {
                                loadmore = false;
                                mAdapter.addFooterView(noMoreView, 0);
                            }
                        }
                    } else {
                        completeLoadmore(true);
                        if (noMoreView.getParent() == null) {
                            loadmore = false;
                            mAdapter.addFooterView(noMoreView, 0);
                        }
                    }

                } catch (Exception e) {
                    loadmoreError(getResources().getString(R.string.str_loaderror));
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                loadmoreError(getResources().getString(R.string.str_loaderror));
            }
        });
    }

//    /**
//     * 给底部添加一个白色的区域
//     *
//     * @param tabH
//     */
//    void addFooterView(int tabH) {
//        if (tabH > 0 && mAdapter != null && tabEmptyView == null && mAdapter.getData().size() > 0) {
//            tabEmptyView = new View(getActivity());
//            tabEmptyView.setBackgroundColor(getResources().getColor(R.color.bg_f5));
//            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, tabH);
//            tabEmptyView.setLayoutParams(params);
//            mAdapter.addFooterView(tabEmptyView);
//        }
//    }

    @Override
    void initAdapte() {
        super.initAdapte();
        needmore = true;
        mLinearRecyclerView.setHasFixedSize(true);
        mAdapter = new SupperDekaronAdapter(mdatas, getContext());
        mLinearRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.re_title) {
                    Object itemEntity = adapter.getItem(position);
                    if (itemEntity instanceof SupperModel) {
                        SupperModel supperModel = (SupperModel) itemEntity;
                        SupperDekaronActivity.start(getActivity(), supperModel.getTopic());

                    }
                } else if (view.getId() == R.id.iv_dekaron) {
                    Object itemEntity = adapter.getItem(position);
                    if (itemEntity instanceof SupperModel) {
                        SupperModel supperModel = (SupperModel) itemEntity;
                        if (supperModel.getTopic() != null && supperModel.getTopic().getMedal() == 1) {
                            RoomPushShortActivity.startActivity(getActivity(), supperModel.getTopic().getId());
                            MobclickAgent.onEvent(getActivity(), "dingxiang_click");
                        }
                    }
                }
//                else if (view.getId() == R.id.discover_live_tv_nick) {
//                    RoomInfoModel roomInfoModel = (RoomInfoModel) adapter.getItem(position);
//                    if ((roomInfoModel != null ? roomInfoModel.getUser() : null) != null) {
//                        ProfileActivity.start(getActivity(), roomInfoModel.getUser().getUid());
//                    }
//                }
            }
        });

        mRefreshLayout.setOnScrollListener(new TwinklingRefreshLayout.OnScrollListener() {
            @Override
            public void onScrolled() {
                LinearLayoutManager mLinearLayoutManager = (LinearLayoutManager) mLinearRecyclerView.getLayoutManager();
                if (mLinearLayoutManager != null) {
                    int lastVisibleItemPosition = mLinearLayoutManager.findLastVisibleItemPosition();
                    LinearLayout linearLayout = (LinearLayout) mLinearLayoutManager.getChildAt(0);
                    LinearLayout endlinearLayout = (LinearLayout) mLinearLayoutManager.findViewByPosition(lastVisibleItemPosition);
                    setWebpShow(linearLayout, true);
                    if (endlinearLayout != null) {
                        setWebpShow(endlinearLayout, false);
                    }
                }
            }
        });
    }

    private void setWebpShow(LinearLayout linearLayout, boolean isfirt) {
        if (linearLayout != null && linearLayout.getChildCount() > 1) {
            View view = linearLayout.getChildAt(1);
            if (view instanceof SupperScrollView) {
                SupperScrollView supperScrollView = (SupperScrollView) view;
                boolean isstop;
                if (isfirt) {
                    isstop = linearLayout.getY() < -(linearLayout.getMeasuredHeight() * 0.6);
                } else {
                    isstop = linearLayout.getY() > mLinearRecyclerView.getBottom() - (linearLayout.getMeasuredHeight() * 0.8);
                }
                supperScrollView.setAntion(isstop ? View.INVISIBLE : View.VISIBLE);

            }
        }
    }

    @Override
    void oncreate() {
        SupperDekaronLayout supperDekaronLayout = new SupperDekaronLayout(getActivity());
        mAdapter.addHeaderView(supperDekaronLayout);
        noMoreView = LayoutInflater.from(getContext()).inflate(R.layout.no_more_layout, mRefreshLayout, false);
//        MobclickAgent.onEvent(getActivity(), "find_hot");
    }
}
